﻿var BaseUrl = "";

var orgChart;


var OChart = {
    OrgChart: null,
    OrgChartId:"",
    InitTree:function(){
        $(".jstree").jstree({
            "core": {
                "check_callback": true,//默认为flase，会导致无法使用修改树结构。
                data: function (obj, callback) {
                    var _self = this;
                    var id = obj.id;
                    Ajax({
                        url: BaseUrl + "/Organizations/GetTree",
                        data: { id: (obj.parent == "#" ||(obj.original&&obj.original.IsOrg))? "" :  obj.id, OrgId: obj.id },
                        success: function (result) {
                            callback.call(_self, result);
                        }
                    });

                }

            },
            "contextmenu": {
                select_node: true,
                show_at_node: true,
                show_Itemed: function (treeNode, items) {
               
                    var node = treeNode.original;
               
                    items.create._disabled = true;
                    items.edit._disabled = true;
                    items.delete._disabled = true;
                    items.checkIn._disabled = true;
                    items.checkOut._disabled = true;
                    items.uncheckOut._disabled = true;
                    if (node.IsOrg) {
                        items.create._disabled = false;
                        console.log(node.id);
                        if (node.id != "000") {
                            items.edit._disabled = false;
                            items.delete._disabled = false;
                        }
                    }
                    else {
                        if (node.IsEdited) {
                            items.edit.label = "修改";
                            items.edit._disabled = false;
                            items.delete._disabled = false;
                            items.checkIn._disabled = false;
                            items.uncheckOut._disabled = false;
                        }
                        else if (!node.IsCheckOut) {
                            items.edit.label = "查看";
                            items.edit._disabled = false;
                            items.checkOut._disabled = false;
                        }
                    
                    }
                    return items;
                },
                "items": {
                    "create": {
                        "label": "新增",
                        "icon": "fa fa-plus",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                            var nodeOriginal1 = inst.get_node(treeNode.reference).original;
                       
                            if (nodeOriginal1.id == "000") {
                                OChart.ModalRemote(inst, treeNode, true, "/organizations/modaledit", "组织架构");
                            }
                            else {
                                OChart.ModalRemote(inst, treeNode, true, "/orgchart/deptedit", "部门");
                            }
                           
                       
                        },
                    },
                    "edit": {
                        "label": "修改",
                        "icon": "fa fa-paste",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                            var nodeOriginal1 = inst.get_node(treeNode.reference).original;
                            if (nodeOriginal1.IsOrg && nodeOriginal1.id == "000") {
                                return;
                            }
                            else if (nodeOriginal1.IsOrg) {
                                OChart.ModalRemote(inst, treeNode, true, "/organizations/modaledit", "组织架构");
                            }
                            else {
                                OChart.ModalRemote(inst, treeNode, false, "/orgchart/deptedit", "部门");
                            }
                            
                     
                        }
                    },
                
                    "delete": {
                        "label": "删除",
                        "icon": "fa fa-trash",
                        "action": function (treeNode) {
                            var tree = jQuery.jstree.reference(treeNode.reference);
                            var node = tree.get_node(treeNode.reference);
                            if (node.original.IsOrg) {
                                if (node.children && node.children.length > 0) {
                                    Notify.Error("组织机构下面存在部门，无法删除");
                                    return;
                                }
                                Notify.Confirm("确定要删除该信息吗？", "删除提示", function () {
                                    Ajax({
                                        url: BaseUrl + "/organizations/Delete",
                                        data: { deleteKeys: node.original.id },
                                        success: function (result, message) {
                                            tree.delete_node(treeNode.reference);
                                        }
                                    });
                                });
                            }
                            else if (!node.original.IsOrg&&node.original.IsEdited) {
                                Notify.Confirm("确定要删除该信息吗？", "删除提示", function () {
                                    Ajax({
                                        url: BaseUrl + "/department/Delete",
                                        data: { DepartmentId: node.original.DepartmentId },
                                        success: function (result, message) {
                                            tree.delete_node(treeNode.reference);
                                        }
                                    });
                                });
                            }
                     
                        }
                    },
                    "checkOut": {
                        "label": "迁出",
                        "icon": "fa fa-sign-out",
                        "action": function (treeNode) {
                            var inst = jQuery.jstree.reference(treeNode.reference);
                            var node = inst.get_node(treeNode.reference);
                            if (!node.original.IsCheckOut) {
                                Notify.Confirm("您确定要调整该部门结构吗，迁出后其他用户将无法操作？", "确认提示", function () {
                                    Ajax({
                                        url: BaseUrl + "/OrgChart/CheckOut",
                                        data: { DepartmentId: node.original.DepartmentId },
                                        success: function (result, message) {
                                            node.icon = "fa fa-user";
                                            node.original.icon = "fa fa-user";
                                            node.original.IsCheckOut = true;
                                            node.original.IsEdited = true;
                                            inst.edit_node(treeNode.reference, node);
                                            OChart.Ajax(node.original.DepartmentId);
                                            // $("#ifrmJobOrgChart").attr("src", "@Url.Content("~/ORG/ORGChart/Index")?id=" + currentNode.data.DepartmentId);
                                        }
                                    });
                                });
                            }
                            else {
                                Notify.Error("该部门已迁出或者您无权迁出");
                            }
                        }
                    },
                    "checkIn": {
                        "label": "迁入",
                        "icon": "fa fa-sign-in",
                        "action": function (treeNode) {
                            var tree = jQuery.jstree.reference(treeNode.reference);
                            var node = tree.get_node(treeNode.reference);
                            if (node.original.IsEdited)
                            {
                                Notify.Confirm("您确定要迁入该部门吗，迁入后将永久覆盖原有结构？", "确认提示", function () {
                                    Ajax({
                                        url:BaseUrl+ "/OrgChart/CheckIn",
                                        data: { DepartmentId: node.original.DepartmentId },
                                        success: function (result, message) {
                                            node.icon = "fa fa-check";
                                            node.original.IsCheckOut = false;
                                            node.original.IsEdited = false;
                                            tree.edit_node(treeNode.reference, node);
                                        
                                            OChart.Ajax(node.original.DepartmentId);
                                            //$("#ifrmJobOrgChart").attr("src", "@Url.Content("~/ORG/ORGChart/Index")?id=" + currentNode.data.DepartmentId);
                                        }
                                    });
                                });
                            }
                            else {
                                Notify.Error("该部门您无权操作");
                            }
                        }
                    },
                    "uncheckOut": {
                        "label": "撤销迁出",
                        "icon": "fa fa-unlock",
                        "_disabled":true,
                        "action": function (treeNode) {
                            var tree = jQuery.jstree.reference(treeNode.reference);
                            var node = tree.get_node(treeNode.reference);
                            if (node.original.IsEdited)
                            {
                                Notify.Confirm("您确定要撤销迁出吗，撤销后会恢复原有结构？", "确认提示", function () {
                                    Ajax({
                                        url:BaseUrl+ "/OrgChart/Revoke",
                                        data: { DepartmentId: node.original.DepartmentId },
                                        success: function (result, message) {
                                            node.icon = "fa fa-check";
                                            node.original.IsCheckOut = false;
                                            node.original.IsEdited = false;
                                            tree.edit_node(treeNode.reference, node);
                                        
                                            OChart.Ajax(node.original.DepartmentId);
                                            //$("#ifrmJobOrgChart").attr("src", "@Url.Content("~/ORG/ORGChart/Index")?id=" + currentNode.data.DepartmentId);
                                        }
                                    });
                                });
                            }
                        }
                    }

                }
            },

            "plugins": ["wholerow", "contextmenu"]
        }).on('activate_node.jstree', function (obj, e) {
            if (e.node.original.IsOrg)
            {
                return false;
            }
            OChart.Ajax(e.node.id);
     
        });
    },
    ModalRemote:function(tree, treeNode, isAdd,url,title){
        var nodeOriginal = tree.get_node(treeNode.reference).original;
        var node = tree.get_node(treeNode.reference);
        if (nodeOriginal.IsOrg && nodeOriginal.OrgId == "000" && !isAdd) {
            Notify.Error("根节点不允许修改");
            return false;
        }
        //if (nodeOriginal.IsOrg && !isAdd) {
        //    Notify.Error("组织机构不允许修改");
        //    return false;
        //}
        if (!nodeOriginal.IsOrg && isAdd) {
            Notify.Error("部门不允许新增");
            return false;
        }
        var buttons= [{ id: "close", isClose: true, Name: "关闭" }];
        if (isAdd||(!isAdd &&nodeOriginal.IsEdited))
        {
            buttons.push({
                id: "btnConfirm", cssClass: "btn-primary", isClose: false, Name: "保  存", click: function (modal, modalId) {
                    var itemKeys = "";
                    FormHelper.ajaxSubmit(modal.find("#dynamic-form"), function (result, isSuccess) {
                        if (!isSuccess) {
                            Notify.Error(result);
                            return false;
                        }
                        if (nodeOriginal.IsOrg) {
                            result.parent = nodeOriginal.OrgId;
                        }
                        if (isAdd) {
                            tree.deselect_all(false);
                            if (node.state.loaded) {
                                tree.create_node(nodeOriginal.IsOrg ? nodeOriginal.OrgId : nodeOriginal.ParentId, result);
                            }
                            if (!node.state.opened) {
                                tree.open_node(treeNode.reference);
                            }
                            tree.select_node(result.id);
                           
                        }
                        else {
                            node.original = result;
                            node.icon = "fa fa-user";
                            node.text = result.text;
                            tree.edit_node(treeNode.reference, node);
                      
                        }
                        OChart.Ajax(result.id);
                        modal.modal("hide");
                    },null);
                    return false;
                }
            });
        }
        url = BaseUrl + url + "?t=" + Math.random();

        Notify.Remote({
            Title: title + "编辑",
            remote:  url + "?t=" + Math.random() + (isAdd ? "&OrgId=" + nodeOriginal.id : "&id=" + nodeOriginal.id),
            buttons:buttons,
            loaded: function (modal, id) {
                modal.find("#dynamic-form").CustomForm({
                    isValidate: true,
                    isTable: false
                });


            }
        });
    },
    Ajax:function(departmentid){
        Ajax({
            url: BaseUrl + "/orgchart/index",
            data: { id: departmentid },
            success: function (result) {
                OChart.InitOrgChart(result, "orgChartContent");
            }
        });
    },

    ///初始化
    InitOrgChart: function (result, orgChartDivId,disabled) {
        this.OrgChartId = orgChartDivId;
        var btnAdd = '<g data-action="add" class="btn orgchart-node-click" transform="matrix(0.14,0,0,0.14,0,0)"><rect style="opacity:0" x="0" y="0" height="300" width="300" /><path  fill="#686868" d="M149.996,0C67.157,0,0.001,67.158,0.001,149.997c0,82.837,67.156,150,149.995,150s150-67.163,150-150 C299.996,67.156,232.835,0,149.996,0z M149.996,59.147c25.031,0,45.326,20.292,45.326,45.325 c0,25.036-20.292,45.328-45.326,45.328s-45.325-20.292-45.325-45.328C104.671,79.439,124.965,59.147,149.996,59.147z M168.692,212.557h-0.001v16.41v2.028h-18.264h-0.864H83.86c0-44.674,24.302-60.571,40.245-74.843 c7.724,4.15,16.532,6.531,25.892,6.601c9.358-0.07,18.168-2.451,25.887-6.601c7.143,6.393,15.953,13.121,23.511,22.606h-7.275 v10.374v13.051h-13.054h-10.374V212.557z M218.902,228.967v23.425h-16.41v-23.425h-23.428v-16.41h23.428v-23.425H218.9v23.425 h23.423v16.41H218.902z"/></g>';
        var btnEdit = '<g data-action="edit" class="btn orgchart-node-click" transform="matrix(0.14,0,0,0.14,50,0)"><rect style="opacity:0" x="0" y="0" height="300" width="300" /><path fill="#686868" d="M149.996,0C67.157,0,0.001,67.161,0.001,149.997S67.157,300,149.996,300s150.003-67.163,150.003-150.003 S232.835,0,149.996,0z M221.302,107.945l-14.247,14.247l-29.001-28.999l-11.002,11.002l29.001,29.001l-71.132,71.126 l-28.999-28.996L84.92,186.328l28.999,28.999l-7.088,7.088l-0.135-0.135c-0.786,1.294-2.064,2.238-3.582,2.575l-27.043,6.03 c-0.405,0.091-0.817,0.135-1.224,0.135c-1.476,0-2.91-0.581-3.973-1.647c-1.364-1.359-1.932-3.322-1.512-5.203l6.027-27.035 c0.34-1.517,1.286-2.798,2.578-3.582l-0.137-0.137L192.3,78.941c1.678-1.675,4.404-1.675,6.082,0.005l22.922,22.917 C222.982,103.541,222.982,106.267,221.302,107.945z"/></g>';
        var btnDel = '<g data-action="delete" class="btn orgchart-node-click" transform="matrix(0.14,0,0,0.14,100,0)"><rect style="opacity:0" x="0" y="0" height="300" width="300" /><path fill="#686868" d="M112.782,205.804c10.644,7.166,23.449,11.355,37.218,11.355c36.837,0,66.808-29.971,66.808-66.808 c0-13.769-4.189-26.574-11.355-37.218L112.782,205.804z"/> <path stroke="#686868" fill="#686868" d="M150,83.542c-36.839,0-66.808,29.969-66.808,66.808c0,15.595,5.384,29.946,14.374,41.326l93.758-93.758 C179.946,88.926,165.595,83.542,150,83.542z"/><path stroke="#686868" fill="#686868" d="M149.997,0C67.158,0,0.003,67.161,0.003,149.997S67.158,300,149.997,300s150-67.163,150-150.003S232.837,0,149.997,0z M150,237.907c-48.28,0-87.557-39.28-87.557-87.557c0-48.28,39.277-87.557,87.557-87.557c48.277,0,87.557,39.277,87.557,87.557 C237.557,198.627,198.277,237.907,150,237.907z"/></g>';
        // +50 var btnDetails = '<g class="btn" data-action="details" transform="matrix(0.14,0,0,0.14,150,0)"><rect style="opacity:0" x="0" y="0" height="300" width="300"></rect><path fill="#686868" d="M139.414,96.193c-22.673,0-41.056,18.389-41.056,41.062c0,22.678,18.383,41.062,41.056,41.062 c22.678,0,41.059-18.383,41.059-41.062C180.474,114.582,162.094,96.193,139.414,96.193z M159.255,146.971h-12.06v12.06 c0,4.298-3.483,7.781-7.781,7.781c-4.298,0-7.781-3.483-7.781-7.781v-12.06h-12.06c-4.298,0-7.781-3.483-7.781-7.781 c0-4.298,3.483-7.781,7.781-7.781h12.06v-12.063c0-4.298,3.483-7.781,7.781-7.781c4.298,0,7.781,3.483,7.781,7.781v12.063h12.06 c4.298,0,7.781,3.483,7.781,7.781C167.036,143.488,163.555,146.971,159.255,146.971z"></path><path stroke="#686868" fill="#686868" d="M149.997,0C67.157,0,0.001,67.158,0.001,149.995s67.156,150.003,149.995,150.003s150-67.163,150-150.003 S232.836,0,149.997,0z M225.438,221.254c-2.371,2.376-5.48,3.561-8.59,3.561s-6.217-1.185-8.593-3.561l-34.145-34.147 c-9.837,6.863-21.794,10.896-34.697,10.896c-33.548,0-60.742-27.196-60.742-60.744c0-33.548,27.194-60.742,60.742-60.742 c33.548,0,60.744,27.194,60.744,60.739c0,11.855-3.408,22.909-9.28,32.256l34.56,34.562 C230.185,208.817,230.185,216.512,225.438,221.254z"></path></g>';
        getOrgChart.themes.monica.box += '<g transform="matrix(1,0,0,1,350,10)">'
                + btnAdd
                + btnEdit
                + btnDel
              //  + btnDetails
                + '</g>';

        orgChart = new getOrgChart($("#" + orgChartDivId)[0], {
            primaryFields: ["SourceName", "JobFunctionName"],
            idField: "JobFunctionId",
            theme: "monica",
            parentIdField: "ParentId",
            enableEdit: false,
            enableDetailsView: false,
            renderNodeEvent: function (sender, args) {
                if (args.node.data.JobFunctionType == 1) {
                    args.content[2] = args.content[2].replace(args.node.data.SourceName, "部门:" + args.node.data.SourceName);
                    args.content[1] = args.content[1].replace("<path", "<path  style='fill:#af3e00; stroke:#af3e00;'");

                }
                else if (args.node.data.JobFunctionType == 2) {
                    args.content[2] = args.content[2].replace(args.node.data.SourceName, "助理:" + args.node.data.SourceName);
                    args.content[1] = args.content[1].replace("<path", "<path  style='fill:#af3e00; stroke:#af3e00;'");
                    args.content[3] = args.content[3].replace(args.node.data.JobFunctionName, "职位:" + args.node.data.JobFunctionName);
                }
                else {
                    args.content[2] = args.content[2].replace(args.node.data.SourceName, "岗位:" + args.node.data.SourceName);
                    args.content[3] = args.content[3].replace(args.node.data.JobFunctionName, "职位:" + args.node.data.JobFunctionName);
                }
            },

            updatedEvent: function () {
                OChart.InitBtnClick(result.Department.IsEdited, disabled);
            },
            boxSizeInPercentage: {
                minBoxSize: {
                    width: 5,
                    height: 5
                },
                boxSize: {
                    width: 20,
                    height: 20
                },
                maxBoxSize: {
                    width: 100,
                    height: 100
                }
            },
            dataSource: result.JobData
        });
        OChart.InitBtnClick(result.Department.IsEdited, disabled);
    },
    getNodeByClickedBtn: function (el) {
        while (el.parentNode) {
            el = el.parentNode;
            if (el.getAttribute("data-node-id"))
                return el;
        }
        return null;
    },
    InitBtnClick: function (checkstatus, disabled) {
        checkstatus = checkstatus && !disabled;
        var btns = document.getElementsByClassName("orgchart-node-click");
        for (var i = 0; i < btns.length; i++) {
            btns[i].addEventListener("click", function () {
                var nodeElement = OChart.getNodeByClickedBtn(this);
                var action = this.getAttribute("data-action");
                var id = nodeElement.getAttribute("data-node-id");
                var node = orgChart.nodes[id];
                node.data.JobFunctionId = id;
                node.data.ParentId = node.pid;
                switch (action) {
                    case "add":
                        if (!node.data.SourceId || node.data.SourceId == "") {
                            Notify.Error("请先保存该岗位信息后在进行操作");
                            return false;
                        }
                        if (node.data.JobFunctionType != 0) {
                            Notify.Error("非岗位下面无法新建岗位");
                            return false;
                        }
                        if (checkstatus) {
                            OChart.Add(node, checkstatus);

                        }
                        break;
                    case "edit":
                        OChart.Edit(node, checkstatus);
                        break;
                    case "delete":
                        if (node.pid == null || node.pid == "") {
                            Notify.Error("顶级岗位无法删除");
                            return false;
                        }
                        OChart.Delete(node, checkstatus, id);
                        break;
                }
            });
        }
    },
    Add: function (node, checkstatus) {
        node.data.JobFunctionId = "";
        node.data.ParentId = node.id;
        OChart.JobRemote(node, true, function (result) {
            orgChart.insertNode(node.id, result, result.JobFunctionId);
        }, checkstatus);
    },
    Edit: function (node, checkstatus) {
        OChart.JobRemote(node, false, function (result) {
            orgChart.updateNode(node.id, node.pid, result);
        }, checkstatus);
    },
    Delete: function (node, checkstatus, id) {
        if (!checkstatus)
        {
            Notify.Error("部门未迁出，无法删除");
            return false;
        }
        Notify.Confirm("确定要删除该岗位吗？", "删除提示", function () {
            Ajax({
                url: BaseUrl+"/OrgChart/JobDelete",
                data: { jobid: node.data.JobFunctionId, deptId: node.data.DepartmentId },
                success: function (result) {
                    orgChart.removeNode(id);
                }
        });
    });
       
    },
    JobRemote: function (node, isAdd, func, ischeckout) {
        buttons = [{ id: "close", isClose: true, Name: "关闭" }];
        if (ischeckout)
        {
            buttons.push({
                id: "btnConfirm", cssClass: "btn-primary", isClose: false, Name: "保  存", click: function (modal, modalId) {
                    var itemKeys = "";
                    FormHelper.ajaxSubmit(modal.find("#job-dynamic-form"), function (result) {
                        func(result);
                        modal.modal("hide");
                    },null);
                    return false;
                }
            });
        }
        Notify.Remote({
            Title: "岗位编辑",
            remote: BaseUrl + "/orgchart/JobEdit?t=" + Math.random() + (isAdd ? "" : "&JobFunctionId=" + node.data.JobFunctionId) + "&DepartmentId=" + node.data.DepartmentId + "&ParentId=" + node.data.ParentId + "&OrgId=" + node.data.OrgId,
            buttons: buttons,
            loaded: function (modal, id) {
                modal.find("#job-dynamic-form").CustomForm({
                    isValidate: true,
                    isTable: false,
                    Init:true
                });
                modal.find("#JobFunctionType").on("select2:select", function (e) {
                    var type = modal.find("#JobFunctionType").val();
                    modal.find("label[for='SourceId']").html(modal.find("#JobFunctionType").children("option:selected").text());
                    modal.find(".JobFunctionInfo").css({ "display": type == "1" ? "none" : "block" });
                    modal.find("#JobGradeId").val("");
                    modal.find(".ajax-select").empty("");
                    modal.find("input[name='JobFunctionName']").val("");
                    modal.find("input[name='SourceName']").val("");
                
                });
                modal.find(".ajax-select").select2({
                    width:"100%",
                    ajax: {
                        url: BaseUrl + '/OrgChart/GetResource',
                        type:"POST",
                        data: function (params) {
                            var query = {
                                keyword: params.term,
                                orgId: node.data.OrgId,
                                type: "public",
                                qtype: modal.find("#JobFunctionType").children("option:selected").val()
                            }
                            return query;
                        },
                        processResults: function (result) {
                            var type = modal.find("#JobFunctionType").children("option:selected").val();
                            var resultData = [];
                            if (result.Data != null && result.Data.length > 0)
                            {
                                for (var i = 0; i < result.Data.length; i++) {
                                    if (type == "0") {
                                        resultData.push({ id: result.Data[i].UserId, text: result.Data[i].UserName });
                                    }
                                    else {
                                        resultData.push({ id: result.Data[i].DepartmentId, text: result.Data[i].DepartmentName });
                                    }
                                }
                            }
                            return {
                                results: resultData
                            };
                        }
                    }
                });
                modal.find("#JobGradeId").on("select2:select", function (e) {
                    //.replace("&nbsp;","")
                    var text = $(this).children("option:selected").text().replace("&nbsp;", "");
           
                   modal.find("input[name='JobFunctionName']").val(text);

                });
                modal.find(".ajax-select").on("select2:select", function (e) {
                
                    modal.find("input[name='SourceName']").val($(this).children("option:selected").text());

                });
                modal.find(".select2,.ajax-select").on("select2:open", function () { $(".select2-container--open").css({ "z-index": "9999" }); });

            }
        })
    }
}
$.fn.modal.Constructor.prototype.enforceFocus = function () { };